﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FatHibernation.DataInterface;

namespace FatHibernation.DataSession
{
    public enum TransactionMode
    {
        READ,
        WRITE
    }

    public class WorkUnit : IDisposable
    {

        private IDataSessionHandler _sessionHandler;
        private bool _commited;

        /// <summary>
        /// Used to handle database transactions.
        /// If Commit is not called before the WorkUnit is disposed it rollbacks the current transaction.
        /// </summary>
        /// <param name="sessionHandler"></param>
        /// <param name="transactionMode"></param>
        public WorkUnit(IDataSessionHandler sessionHandler, TransactionMode transactionMode)
        {
            _sessionHandler = sessionHandler;
            _commited = false;

            if(!_sessionHandler.IsSessionOpen)
                _sessionHandler.OpenSession();

            if(transactionMode == TransactionMode.WRITE)
            {
                _sessionHandler.BeginWriteTransaction();
            }
            else
            {
                _sessionHandler.BeginReadTransaction();
            }
            
        }

        public void Commit()
        {
            Commit(false);
        }

        public void Commit(bool closeSession)
        {
            _sessionHandler.CommitCurrentTransaction();
            if(closeSession)
                _sessionHandler.CloseSession();
            _commited = true;
        }

        public void Dispose()
        {
            if (!_commited)
                _sessionHandler.RollbackCurrentTransaction();
        }


    }
}